package cn.ctodb.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.ctodb.domain.Content;
import cn.ctodb.repository.ContentRepository;

@Service
public class ContentService {

    @Resource
    private ContentRepository contentRepository;

    public List<Content> getList(Map<String, Object> param) {
        return contentRepository.findByCgId(Long.parseLong(param.get("cgid") + ""));
    }

    public Content get(Long id) {
        return contentRepository.getOne(id);
    }

    public Page<Content> getPage(Pageable pageable) {
        return contentRepository.findAll(pageable);
    }

    public void up(Content content) {
        Content c = get(content.getId());
        c.setTitle(content.getTitle());
        c.setContent(content.getContent());
        c.setCreateDate(content.getCreateDate());
        c.setTags(content.getTags());
        c.setCgId(content.getCgId());
        c.setUserId(content.getUserId());
        c.setImg(content.getImg());
        initContent(c);
    }

    public void add(Content content) {
        content.setCommCount(0L);
        content.setViewCount(0L);
        initContent(content);
        contentRepository.save(content);
    }

    private void initContent(Content c) {
        Document doc = Jsoup.parse(c.getContent());
        if (StringUtils.isEmpty(c.getIntro())) {
            String A_INTRO = doc.text();
            // 简介
            A_INTRO = A_INTRO.replaceAll("[\r\n]", "");
            A_INTRO = A_INTRO.substring(0, A_INTRO.length() > 300 ? 300 : A_INTRO.length());
            c.setIntro(A_INTRO);
        }
        if (StringUtils.isEmpty(c.getImg())) {
            Elements elements = doc.select("img");
            if (elements.size() > 0) {
                String img = elements.get(0).attr("src");
                c.setImg(img);
            }
        }
    }

    public void del(Long id) {
        contentRepository.delete(id);
    }

}
